/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.smart.utils;

import cn.xuyanwu.spring.file.storage.MockMultipartFile;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.entity.ContentType;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

/**
 * @author zhanghong
 * @version FileUtil.java, v 0.1 2023/7/7 12:39 下午 FileUtil Exp $$
 */
@Slf4j
public class FileUtil {

    public static MultipartFile[] base64ToMultipartFile(List<String> listBase64) {
        MultipartFile[] files = new MultipartFile[2];
        try {
            for (int i = 0; i < listBase64.size(); i++) {
                Base64.Decoder decoder = Base64.getMimeDecoder();
                // 去掉base64前缀 data:image/jpeg;base64,
                byte[] b = decoder.decode(listBase64.get(i));
                // 处理数据
                for (int j = 0; j < b.length; ++j) {
                    if (b[j] < 0) {
                        b[j] += 256;
                    }
                }
                InputStream inputStream = new ByteArrayInputStream(b);
                String string = UUID.randomUUID().toString().concat(".png");
                MultipartFile file = new MockMultipartFile(string, string, ContentType.IMAGE_PNG.toString(), inputStream);
                if (ObjectUtils.isNotEmpty(file)) {
                    files[i] = file;
                }
                inputStream.close();
            }
            return files;
        } catch (Exception e) {
            log.info("base64ToMultipartFile - {}", e.getStackTrace());
            return files;
        }
    }

    public static MultipartFile base64ToMultipartFile(String base64) {
        MultipartFile[] multipartFiles = base64ToMultipartFile(Lists.newArrayList(base64));
        return multipartFiles[0];
    }
}
